def plus(x,y): return x+y
plus.code = "add"

def subtract(x,y): return x-y
subtract.code = "sub"

def multiply(x,y): return x*y
multiply.code = "mul"

def divide(x,y): return x/y
divide.code = "div"

def makenode(op):
	class node:
		def __init__(self, op1, op2):
			self.__operand1 = op1
			self.__operand2 = op2
		def eval(self):
			return op(self.__operand1.eval(), \
				  self.__operand2.eval())
		def code(self):
			return self.__operand1.code()+\
				self.__operand2.code()+\
				op.code+"\n"
	return node

class leaf:
	def __init__(self, value):
		self.__value = value
	def eval(self):
		return ord(self.__value)-ord('0')
	def code(self):
		return "store "+self.__value+"\n"

translator =   {'+':makenode(plus),
		'-':makenode(subtract),
		'*':makenode(multiply),
		'/':makenode(divide) }
translator.update({str(x):leaf(str(x)) for x in range(10)})

class calculator:
	def __init__(self, expr):
		self.__root, dropped = self.__convert(expr, 0)

	def __convert(self, expr, n):
		if n<len(expr):
			print("in recursion, expr:{0} n:{1}".format(expr, n))
			if expr[n] in {'+', '-', '*', '/'}:
				op1,n1 = self.__convert(expr, n+1)
				op2,n2 = self.__convert(expr, n1+1)
				print("\tin recursion, node-> n1:{0} n2:{1}".format(n1,n2))
				print("\t                     n = "+str(n))
				return translator[expr[n]](op1,op2),n2
			else: 
				print("\tin recursion, leaf-> expr[n]:{0}".format(expr[n]))
				return translator[expr[n]],n

	def eval(self): return self.__root.eval()
	def code(self): return self.__root.code()

if __name__ == "__main__":
	print("test +2*-53/63 --> ((6/3)*(5-3))+2")
	calc = calculator("+2*-53/63")
	print(calc.eval())
	print(calc.code())

